/**
 * @see [description](https://mp.weixin.qq.com/debug/wxadoc/dev/api/open.html#wxgetuserinfoobject)
 */
import get from '../cache/get';
import set from '../cache/set';

const WX_USER_INFO = 'feidao-wx-user-info';

export default async function get_user_info(withCredentials?: boolean, lang?: string) {
	const user_info = await get<wx.UserInfo>(WX_USER_INFO);
	if (!user_info) {
		console.log('could get userInfo from storage, call wx.getUserInfo');
		return await new Promise<{
			msg: wx.UserInfo;
			success: boolean;
		}>((resolve) => {
			wx.getUserInfo({
				lang,
				withCredentials,
				async success(res) {
					const u_i = res.userInfo;
					try {
						await set(WX_USER_INFO, u_i);
					} finally {
						resolve({
							msg: u_i,
							success: true
						});
					}
				},
				fail(res) {
					resolve({
						msg: res,
						success: false
					});
				}
			});
		});
	} else {
		return user_info;
	}
}
